package com.system.framework.security.service;

import com.system.common.constant.Constants;
import com.system.common.constant.UserConstants;
import com.system.common.exception.CustomException;
import com.system.common.exception.user.*;
import com.system.common.utils.MessageUtils;
import com.system.common.utils.SecurityUtils;
import com.system.common.utils.ServletUtils;
import com.system.common.utils.StringUtils;
import com.system.common.utils.ip.IpUtils;
import com.system.framework.manager.AsyncManager;
import com.system.framework.manager.factory.AsyncFactory;
import com.system.framework.redis.RedisCache;
import com.system.framework.security.LoginRequest;
import com.system.framework.security.LoginUser;
import com.system.framework.thradlocal.ContextUserInfoHolder;
import com.system.framework.thradlocal.UserContextInfo;
import com.system.framework.web.domain.Result;
import com.system.module.system.entity.SysUser;
import com.system.module.system.service.ISysConfigService;
import com.system.module.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 登录校验方法
 *
 * @author 程序员Mars
 */
@Component
@AllArgsConstructor
public class SysLoginService {
    private final TokenService tokenService;

    private final ISysUserService sysUserService;

    private final RedisCache redisCache;

    private final SysPermissionService permissionService;

    private final ISysConfigService configService;

    private final AuthenticationManager authenticationManager;


    /**
     * 登录验证
     *
     * @param loginRequest loginRequest
     * @return 结果
     */
    public String login(LoginRequest loginRequest) {
        // 验证码校验
        this.validateCaptcha(loginRequest.getUsername(), loginRequest.getCode(), loginRequest.getUuid());
        // 登录前置校验
        this.loginPreCheck(loginRequest.getUsername(), loginRequest.getPassword());
        // 用户验证
        Authentication authentication = this.getAuthentication(loginRequest);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginRequest.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        ContextUserInfoHolder.set(UserContextInfo.builder().userId(loginUser.getUser().getUserId()).nickName(loginUser.getUser().getNickName()).build());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    private Authentication getAuthentication(LoginRequest loginRequest) {
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginRequest.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginRequest.getUsername(), Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        return authentication;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    public void register(String username, String password, String mobile, String type) {
        SysUser sysUser = new SysUser();
        sysUser.setAvatar("");
        sysUser.setDeptId(103L);
        sysUser.setNickName(username);
        sysUser.setUserName(username);
        sysUser.setPhonenumber(mobile);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUser.setStatus("0");
        sysUser.setSex("1");
        sysUser.setDelFlag("0");
        sysUser.setEmail("850994222@qq.com");
        if ("11".equals(type)) {
            sysUser.setRoleIds(new Long[]{2L});
        }
        if ("22".equals(type)) {
            sysUser.setRoleIds(new Long[]{100L});
        }
        sysUserService.insertUser(sysUser);


    }

    public Result getUserInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Result ajax = Result.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
}
